<template>
	<view class="dispose-add-page">

		<!-- 表单内容 -->
		<view class="form-card">
			<!-- 单据编号 -->
			<view class="form-item">
				<text class="label required">单据编号</text>
				<text class="value readonly">{{ formData.disposalCode }}</text>
			</view>

			<!-- 单据名称 -->
			<view class="form-item">
				<text class="label">单据名称</text>
				<view class="value">
					<u-input v-model="formData.disposalOrderName" placeholder="请输入" border="none" style="font-size: 32rpx;" />
				</view>
			</view>

			<!-- 处置日期 -->
			<view class="form-item">
				<text class="label required">处置日期</text>
				<view class="value" @click="datePicker.show = true">
					<text class="picker-text">{{ formData.disposalDate || '请选择' }}</text>
					<u-icon name="arrow-right" size="30rpx" color="#999"></u-icon>
				</view>
			</view>

			<!-- 处置类型 -->
			<view class="form-item">
				<text class="label required">处置类型</text>
				<view class="value" @click="showTypePicker = true">
					<text class="picker-text">{{ formData.disposalTypeName || '请选择' }}</text>
					<u-icon name="arrow-right" size="30rpx" color="#999"></u-icon>
				</view>
			</view>

			<!-- 处置人 -->
			<view class="form-item">
				<text class="label required">处置人</text>
				<view class="value" @click="showUserPicker = true">
					<text class="picker-text">{{ formData.disposalUserName || '请选择' }}</text>
					<u-icon name="arrow-right" size="30rpx" color="#999"></u-icon>
				</view>
			</view>

			<!-- 处置金额 -->
			<view class="form-item">
				<text class="label required">处置金额</text>
				<view class="value">
					<u-input v-model="formData.disposalAmount" placeholder="请输入" border="none" type="number" />
				</view>
			</view>

			<!-- 是否解绑标签 -->
			<view class="form-item">
				<text class="label">是否解绑标签</text>
				<view class="value">
					<u-switch v-model="isUnbindTag" activeColor="#2979ff"></u-switch>
				</view>
			</view>

			<!-- 备注 -->
			<view class="form-item">
				<text class="label">备注</text>
				<view class="value">
					<u-input v-model="formData.remark" placeholder="请输入" border="none" />
				</view>
			</view>
		</view>

		<!-- 附件上传 -->
		<view class="attachment-section">
			<view class="section-title">附件</view>
			<view class="attachment-info">
				<text>最多选择10个文件 大小不超过5MB格式为png/jpg/jpeg/pdf/txt/doc/xls的文件</text>
			</view>
			<view class="upload-btn" @click="selectFile">
				<text>选择文件</text>
			</view>
			<!-- 已选文件展示 -->
			<view v-if="attachmentsUpload[0].files.length" class="attachment-list">
				已上传文件：
				<view v-for="(items, index) in attachmentsUpload[0].files" :key="items.id" class="attachment-item">
					<text style="color: red" @click="handleDownFile(items)">{{ items.name }}</text>
					<u-icon name="close" size="30rpx" color="#999" @click="removeAttachment(index)"></u-icon>
				</view>
			</view>
		</view>

		<!-- 资产列表 -->
		<view class="asset-section">
			<view class="section-header">
				<text class="section-title">资产列表</text>
				<text class="asset-count">共计: {{ selectedAssets?.length || 0 }}</text>
			</view>
			<view class="asset-list" v-if="selectedAssets && selectedAssets.length > 0">
				<view class="asset-item" v-for="(item, index) in selectedAssets" :key="index">
					<view class="asset-img-container">
						<image class="asset-img"
							:src="item.image ? `${BASE_URL}/File/GetImage?fileId=${item.image}` : '/static/placeholder.png'"
							mode="aspectFill" />
					</view>
					<view class="asset-info">
						<view class="asset-name">{{ item.assetName }}</view>
						<view class="asset-detail">资产分类: {{ item.assetClassName }}</view>
						<view class="asset-detail">资产编码: {{ item.assetCode }}</view>
						<view class="asset-detail">资产规格: {{ item.specModel }}</view>
					</view>
					<view class="asset-action">
						<u-icon name="close" size="40rpx" color="#999" @click="removeAsset(index)"></u-icon>
					</view>
				</view>
			</view>
			<view class="empty-tip" v-else>
				<text>暂无资产，请点击下方"添加"按钮添加资产</text>
			</view>
		</view>

		<!-- 底部按钮 -->
		<!-- 底部按钮 -->
		<view class="footer-btn">
			<view class="btn-group">
				<view class="btn add-btn" @click="goToSelectAssets">添加</view>
				<view class="btn reset-btn" @click="resetForm">重置</view>
				<view class="btn submit-btn" @click="submitForm">{{ isEdit ? '保存' : '提交' }}</view>
			</view>
		</view>

		<!-- 日期选择器 -->
		<up-datetime-picker :show="datePicker.show" mode="date" v-model="dateTime" closeOnClickOverlay
			@confirm="confirmDate" @cancel="datePickerClose" @close="datePickerClose"></up-datetime-picker>

		<!-- 处置类型选择器 -->
		<u-picker :show="showTypePicker" :columns="[disposalTypes]" @confirm="confirmType"
			@cancel="showTypePicker = false"></u-picker>

		<!-- 处置人选择器 -->
		<u-picker :show="showUserPicker" :columns="[userList]" @confirm="confirmUser"
			@cancel="showUserPicker = false"></u-picker>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		onMounted,
		onUnmounted
	} from 'vue';
	import {
		onLoad
	} from "@dcloudio/uni-app";
	import http, {
		BASE_URL
	} from "@/api/request";
	import {
		t
	} from "@/locale/index.js";
	import fileSys from "@/utils/fileSys";
	import {
		formatDateTime
	} from "@/utils";

	const attachmentsUpload = ref([{
		Fileld: [],
		files: [],
		linkId: "1",
		taskId: "<%assetdisposalmstr.id%>",
	}, ]);

	// 表单数据
	const formData = ref({
		disposalCode: '系统自动生成',
		disposalOrderName: '',
		disposalDate: '',
		disposalType: '',
		disposalTypeName: '',
		disposalUser: '',
		disposalUserName: '',
		disposalAmount: '',
		isUnbindTag: 'NO',
		remark: '',
		attachment: ''
	});

	// 是否解绑标签（开关状态）
	const isUnbindTag = computed({
		get: () => formData.value.isUnbindTag === 'YES',
		set: (val) => {
			formData.value.isUnbindTag = val ? 'YES' : 'NO';
		}
	});

	// 附件列表
	const attachments = ref([]);

	// 选中的资产列表
	const selectedAssets = ref([]);
	const copyselectedAssets = ref([]);

	// 选择器显示状态
	const showDatePicker = ref(false);
	const showTypePicker = ref(false);
	const showUserPicker = ref(false);

	// 处置类型列表
	const disposalTypes = ref([]);

	// 用户列表
	const userList = ref([]);

	// 编辑模式标识
	const isEdit = ref(false);

	// 日期选择器相关
	const datePicker = ref({
		show: false
	});
	// 初始化为当前日期
	const dateTime = ref(Date.now());

	const pageId = ref('');

	// 添加获取页面信息的函数
	const getPageInfo = async () => {
		const data = {
			assetlist: "assetdisposal",
			pageCode: "disposaladd",
		};

		const {
			code,
			isSuccess,
			result
		} = await http.post(
			"/api/page/GetPageInfoByCode",
			data
		);
		if (code && isSuccess) {
			pageId.value = result.page.parentPageId;
		}
	};

	// 修改提交表单函数
	const submitForm = () => {
		// 表单验证
		if (!formData.value.disposalDate) {
			uni.showToast({
				title: '请选择处置日期',
				icon: 'none'
			});
			return;
		}

		if (!formData.value.disposalType) {
			uni.showToast({
				title: '请选择处置类型',
				icon: 'none'
			});
			return;
		}

		// 显示加载中
		uni.showLoading({
			title: isEdit.value ? '保存中...' : '提交中...'
		});

		let data;
		let removedAssets = [];

		const updateData = {
			id: formData.value.id || '',
			disposal_code: formData.value.disposalCode || '',
			disposal_order_name: formData.value.disposalOrderName,
			disposal_user: formData.value.disposalUser,
			disposal_date: formData.value.disposalDate,
			disposal_type: formData.value.disposalType,
			disposal_amount: formData.value.disposalAmount,
			is_unbind_tag: formData.value.isUnbindTag,
			remark: formData.value.remark,
			state: "PENDING_REVIEW",
			attachment: attachmentsUpload.value?.[0]?.files?.length ?
				attachmentsUpload.value[0].files.map((item) => item.id).join(",") :
				"",
		};

		if (isEdit.value) {
			const {
				added,
				removed,
				isSame
			} = diffArraysById(
				selectedAssets.value,
				copyselectedAssets.value,
				"assetCode"
			);
			removedAssets = removed;
			console.log(isSame, added, removed);
			data = {
				pageId: pageId.value,
				methodName: "doSaveTableData",
				saveTableDataRequest: {
					data: {
						insert: {
							assetdisposaldet: {
								data: isSame ?
									[] :
									added.map((item) => ({
										asset_code: item.asset_code,
										pre_disposal_status: item.asset_state
									}))
							}
						},
						update: {
							assetdisposalmstr: {
								...updateData
							},
							assetdisposaldet: {
								data: isSame ?
									[] :
									removed.map((item) => ({
										id: item.id,
										is_deleted: 1,
									}))
							}
						},
						remove: {},
						updateWhere: {},
						removeWhere: {},
						otherData: {
							fileAttachments: attachmentsUpload.value
						},
						savedInvoke: {},
						pageAuths: []
					}
				}
			};
		} else {
			data = {
				pageId: pageId.value,
				methodName: "doSaveTableData",
				saveTableDataRequest: {
					data: {
						insert: {
							assetdisposaldet: {
								data: selectedAssets.value.map(asset => ({
									asset_code: asset.assetCode,
									pre_disposal_status: asset.asset_state
								}))
							},
							assetdisposalmstr: {
								...updateData,
								disposal_code: ''
							}
						},
						update: {
							assetdisposaldet: {
								data: []
							}
						},
						remove: {},
						updateWhere: {},
						removeWhere: {},
						otherData: {
							fileAttachments: attachmentsUpload.value
						},
						savedInvoke: {},
						pageAuths: []
					}
				}
			};
		}

		http.post("/api/module/Invoke", data).then((res) => {
			uni.hideLoading();
			if (res.isSuccess) {
				if (isEdit.value) {
					// Handle added assets (change status to DISPOSING)
					const addedAssets = diffArraysById(
						selectedAssets.value,
						copyselectedAssets.value,
						"assetCode"
					).added;

					if (addedAssets.length > 0) {
						changeAssetState(
							addedAssets.map(item => item.asset_code),
							"DISPOSING"
						);
					}

					// Handle removed assets (restore pre_disposal_status)
					if (removedAssets.length > 0) {
						const statusGroupMap = {};
						removedAssets.forEach(item => {
							if (item.asset_code) {
								const status = item.pre_disposal_status || 'IDLE';
								if (!statusGroupMap[status]) {
									statusGroupMap[status] = [];
								}
								statusGroupMap[status].push(item.asset_code);
							}
						});

						for (const [state, codes] of Object.entries(statusGroupMap)) {
							changeAssetState(codes, state);
						}
					}
				} else {
					// For new submissions, update all assets to DISPOSING
					if (selectedAssets.value.length > 0) {
						changeAssetState(
							selectedAssets.value.map(item => item.asset_code),
							"DISPOSING"
						);
					}
				}
				uni.showToast({
					title: isEdit.value ? '保存成功' : '提交成功',
					icon: 'success'
				});
				uni.$emit('disposalDataChanged');
				setTimeout(() => {
					uni.navigateBack();
				}, 1500);
			} else {
				uni.showToast({
					title: res.error || (isEdit.value ? '保存失败' : '提交失败'),
					icon: 'none'
				});
			}
		}).catch(err => {
			uni.hideLoading();
			console.error(isEdit.value ? '保存处置单失败:' : '新增处置单失败:', err);
			uni.showToast({
				title: '网络异常，请稍后重试',
				icon: 'none'
			});
		});
	};

	const changeAssetState = (codes, state) => {
		let req = {
			interfaceCode: "Assetlist.doUpdateStatusByAssetCodes",
			asset_state: state,
			asset_codes: codes
		};
		http.post("/api/module/Invoke", req).then((res) => {
			if (res.code && res.isSuccess) {
				console.log("资产状态修改成功！")
			}
		});
	};

	// 在onMounted中调用getPageInfo
	onLoad((options) => {
		// 如果有传入disposalCode，则根据disposalCode获取处置详情
		if (options.disposalCode) {
			isEdit.value = true;
			getDisposeDetail(options.disposalCode).then(() => {
				console.log(formData.value);
				if (formData.value.id) {
					getFiles();
				}
			}).catch(err => {
				console.error('获取处置详情失败:', err);
				uni.showToast({
					title: '获取处置详情失败',
					icon: 'none'
				});
			});
		} else {
			formData.value = {
				disposalCode: '系统自动生成',
				disposalOrderName: '',
				disposalDate: '',
				disposalType: '',
				disposalTypeName: '',
				disposalUser: '',
				disposalUserName: '',
				disposalAmount: '',
				isUnbindTag: 'NO',
				remark: '',
				attachment: ''
			};
		}
		if (isEdit.value) {
			uni.setNavigationBarTitle({
				title: t("assetsDisposal.edit")
			});
		} else {
			uni.setNavigationBarTitle({
				title: t("assetsDisposal.add") // 新增时
			});
		}

		// 确保数组已初始化
		if (!selectedAssets.value) selectedAssets.value = [];
		if (!copyselectedAssets.value) copyselectedAssets.value = [];
		if (!attachments.value) attachments.value = [];
		if (!disposalTypes.value) disposalTypes.value = [];
		if (!userList.value) userList.value = [];

		// 获取处置类型列表
		getDisposalTypes();

		// 获取用户列表
		getUserList();

		// 获取页面信息
		getPageInfo();
	});

	// 获取已有附件
	const getFiles = async () => {
		const postData = {
			linkId: "1",
			taskId: formData.value.id,
		};
		console.log(postData);
		const {
			code,
			isSuccess,
			result
		} = await http.post(
			"/api/file/GetTaskLinkedFiles",
			postData
		);
		if (code && isSuccess && result) {
			result.forEach((item) => {
				attachmentsUpload.value[0].files.push({
					id: item.id,
					name: item.fileName + "  " + item.userName + "  " + item.creationTime,
					url: `/File/Download?fileId=` + item.id,
				});
			});
		}
	};


	function diffArraysById(newList, oldList, key = "assetCode") {
		const newMap = new Map(newList.map((item) => [item[key], item]));
		const oldMap = new Map(oldList.map((item) => [item[key], item]));

		const added = newList.filter((item) => !oldMap.has(item[key]));
		const removed = oldList.filter((item) => !newMap.has(item[key]));

		let isSame = added.length === 0 && removed.length === 0;

		if (isSame) {
			for (const [id, newItem] of newMap.entries()) {
				const oldItem = oldMap.get(id);
				if (JSON.stringify(newItem) !== JSON.stringify(oldItem)) {
					isSame = false;
					break;
				}
			}
		}

		return {
			added,
			removed,
			isSame
		};
	}

	// 获取处置详情
	const getDisposeDetail = (disposalCode) => {
		// 显示加载中
		uni.showLoading({
			title: '加载中...'
		});

		// 构建请求参数
		const data = {
			"pageCode": "assetdisposal",
			"params": {
				"args": [{
						"name": "interfaceCode",
						"value": "assetdisposal.getAssetDisposalOrderDetails"
					},
					{
						"name": "disposalCode",
						"value": disposalCode
					}
				]
			},
			"methodName": "getAssetDisposalOrderDetails"
		};

		// 返回Promise
		return http.post("/api/module/Invoke", data).then((res) => {
			uni.hideLoading();
			if (res.isSuccess && res.result) {
				// 获取主单据信息和资产列表
				const mstr = res.result.assetDisposalMstr || {};
				const assetList = res.result.assetDetVOs || [];

				// 更新表单数据
				formData.value = {
					id: mstr.id || '',
					disposalCode: mstr.disposalCode || disposalCode,
					disposalOrderName: mstr.disposalOrderName || '',
					disposalDate: mstr.disposalDate || '',
					disposalType: mstr.disposalType || '',
					disposalTypeName: mstr.disposalTypeName || '',
					disposalUser: mstr.disposalUser || '',
					disposalUserName: mstr.disposalUserName || '',
					disposalAmount: mstr.disposalAmount || '',
					isUnbindTag: mstr.isUnbindTag || 'NO',
					remark: mstr.remark || '',
					attachment: mstr.attachment || '',
					state: mstr.state || '',
					stateName: mstr.stateName || ''
				};

				// 更新选中的资产列表
				selectedAssets.value = assetList.map(asset => ({
					id: asset.id,
					assetId: asset.assetId,
					assetName: asset.assetName,
					assetClassName: asset.assetClassName,
					assetCode: asset.assetCode,
					specModel: asset.specModel,
					image: asset.image ? asset.image.trim() : '/static/placeholder.png'
				}));
				copyselectedAssets.value = JSON.parse(JSON.stringify(
					selectedAssets.value.map((item) => ({
						...item
					}))
				));

				// 如果有附件，也需要处理附件
				if (mstr.attachment) {
					// 处理附件...
					attachments.value = [{
						name: '已上传附件',
						id: mstr.attachment
					}];
				}

				return res.result; // 返回结果
			} else {
				uni.showToast({
					title: res.error || '获取详情失败',
					icon: 'none'
				});
				throw new Error(res.error || '获取详情失败');
			}
		}).catch(err => {
			uni.hideLoading();
			console.error('获取处置详情失败:', err);
			uni.showToast({
				title: '网络异常，请稍后重试',
				icon: 'none'
			});
			throw err; // 重新抛出错误
		});
	};

	// 获取处置类型列表
	const getDisposalTypes = () => {
		const data = {
			code: "getAssetDisposalOrderAssetTypeList",
			allColumnFilter: true,
			filters: [],
			permissionKey: ""
		};

		http.post("/api/module/GetViewTable", data).then((res) => {
			if (res.isSuccess && res.result && res.result.viewTable) {
				// 适配接口返回的viewTable
				disposalTypes.value = res.result.viewTable.map(item => ({
					text: item.disposal_type_name,
					value: item.id
				}));
			}
		}).catch(err => {
			console.error('获取处置类型失败:', err);
			uni.showToast({
				title: '获取处置类型失败',
				icon: 'none'
			});
		});
	};

	// 获取用户列表
	const getUserList = () => {
		const data = {
			code: "Sys_GetUserNameById",
			filters: [],
			allColumnFilter: true,
			tableFilters: []
		};

		http.post("/api/module/GetViewTable", data).then((res) => {
			if (res.isSuccess && res.result && res.result.viewTable) {
				userList.value = res.result.viewTable.map(item => ({
					text: item.text,
					value: item.id
				}));
			}
		}).catch(err => {
			console.error('获取用户列表失败:', err);
			uni.showToast({
				title: '获取用户列表失败',
				icon: 'none'
			});
		});
	};

	// 确认选择处置类型
	const confirmType = (e) => {
		const selectedType = e.value[0];
		formData.value.disposalType = selectedType.value;
		formData.value.disposalTypeName = selectedType.text;
		showTypePicker.value = false;
	};

	// 确认选择处置人
	const confirmUser = (e) => {
		const selectedUser = e.value[0];
		formData.value.disposalUser = selectedUser.value;
		formData.value.disposalUserName = selectedUser.text;
		showUserPicker.value = false;
	};

	// 选择文件
	const chooseFile = () => {
		if (!attachments.value) {
			attachments.value = [];
		}

		if (attachments.value.length >= 10) {
			uni.showToast({
				title: '最多只能上传10个文件',
				icon: 'none'
			});
			return;
		}

		uni.chooseFile({
			count: 10 - attachments.value.length,
			type: 'all',
			extension: ['.png', '.jpg', '.jpeg', '.pdf', '.txt', '.doc', '.xls'],
			success: (res) => {
				// 处理选择的文件
				const files = res.tempFiles;

				// 检查文件大小
				const validFiles = files.filter(file => file.size <= 5 * 1024 * 1024);
				if (validFiles.length < files.length) {
					uni.showToast({
						title: '部分文件超过5MB，已过滤',
						icon: 'none'
					});
				}

				// 添加到附件列表
				validFiles.forEach(file => {
					attachments.value.push({
						name: file.name,
						path: file.path,
						size: file.size
					});
				});

				// 上传文件
				uploadFiles(validFiles);
			}
		});
	};

	// 上传文件
	const uploadFiles = (files) => {
		// 显示加载中
		uni.showLoading({
			title: '上传中...'
		});

		// 这里应该是调用上传文件的接口
		// 模拟上传成功
		setTimeout(() => {
			uni.hideLoading();
			uni.showToast({
				title: '上传成功',
				icon: 'success'
			});

			// 实际项目中应该获取上传后的文件ID
			formData.value.attachment = 'file-id-123';
		}, 1000);
	};

	// 替换现有的 chooseFile 方法
	const selectFile = () => {
		if (attachmentsUpload.value[0].files.length === 10) {
			uni.showToast({
				title: "超出限制！",
				icon: "error",
			});
		} else {
			fileSys().then((res) => {
				const userInfo = JSON.parse(uni.getStorageSync("userInfo"));
				attachmentsUpload.value[0].files.push({
					id: res[0].id,
					name: (res[0].fileName || "未知文件") +
						"  " +
						userInfo.name +
						"  " +
						formatDateTime(new Date()),
					url: `/File/Download?fileId=` + res[0].id,
				});
			});
		}
		setTimeout(() => {
			uni.hideLoading();
		}, 1500);
	};

	// 添加文件下载方法
	const handleDownFile = (items) => {
		uni.downloadFile({
			url: BASE_URL + items.url,
			success: (res) => {
				if (res.statusCode === 200) {
					plus.runtime.openFile(res.tempFilePath, {}, (e) => {
						uni.showModal({
							title: "无法打开文件",
							content: "请安装 WPS Office 或 QQ 浏览器等可打开该文件的应用",
							confirmText: "去安装",
							success: (modalRes) => {
								if (modalRes.confirm) {
									try {
										plus.runtime.openURL('market://details?id=com.tencent.mtt', () => {
											plus.runtime.openURL('https://browser.qq.com');
										});
									} catch (e) {
										plus.runtime.openURL('https://browser.qq.com');
									}
								}
							},
						});
					});
				}
			},
			fail: (err) => {
				console.error("下载失败", err);
				uni.showToast({
					title: "下载失败",
					icon: "none"
				});
			},
		});
	};

	// 移除附件方法
	const removeAttachment = (index) => {
		attachmentsUpload.value[0].files.splice(index, 1);
	};

	// 跳转到选择资产页面
	const goToSelectAssets = () => {
		uni.navigateTo({
			url: '/components/assetsAddList/index'
		});
	};

	// 监听资产选择事件
	onMounted(() => {
		// 监听资产选择事件和选择资产页面返回的数据
		uni.$on('assetSelected', handleSelectAssets);
	});

	onUnmounted(() => {
		// 移除事件监听
		uni.$off('assetSelected', handleSelectAssets);
	});

	// 处理选择资产页面返回的数据
	const handleSelectAssets = (assets) => {
		if (Array.isArray(assets) && assets.length > 0) {
			if (!selectedAssets.value) selectedAssets.value = [];

			// 转换资产数据格式
			const formattedAssets = assets.map(asset => ({
				id: asset.id,
				assetId: asset.id,
				assetName: asset.asset_name,
				assetClassName: asset.asset_category,
				assetCode: asset.asset_code,
				specModel: asset.spec_model,
				image: asset.image ? asset.image.trim() : '/static/placeholder.png'
			}));

			// 合并选中的资产，避免重复
			const existingIds = selectedAssets.value.map(item => item.id);
			const newAssets = formattedAssets.filter(asset => !existingIds.includes(asset.id));

			selectedAssets.value = [...selectedAssets.value, ...newAssets];
		}
	};

	// 移除资产
	const removeAsset = (index) => {
		selectedAssets.value.splice(index, 1);
	};

	// 重置表单
	const resetForm = () => {
		formData.value = {
			disposalCode: '系统自动生成',
			disposalOrderName: '',
			disposalDate: '',
			disposalType: '',
			disposalTypeName: '',
			disposalUser: '',
			disposalUserName: '',
			disposalAmount: '',
			isUnbindTag: 'NO',
			remark: '',
			attachment: ''
		};
		attachments.value = [];
		selectedAssets.value = [];
	};

	// 日期选择器关闭
	const datePickerClose = () => {
		datePicker.value.show = false;
	};

	// 确认日期选择
	const confirmDate = (e) => {
		// 处理日期值，确保它是有效的
		let timestamp;

		// 处理不同格式的日期返回值
		if (typeof e === 'object') {
			if (e.value !== undefined) {
				timestamp = e.value; // 处理 {value: timestamp, mode: 'date'} 格式
			} else if (e.result !== undefined) {
				timestamp = e.result; // 处理 {result: timestamp} 格式
			} else {
				timestamp = Date.now(); // 默认使用当前时间
			}
		} else {
			timestamp = e; // 直接使用传入的值
		}

		// 使用时间戳创建日期对象
		const date = new Date(timestamp);

		// 检查日期是否有效
		if (isNaN(date.getTime())) {
			console.error('无效的日期值:', e);
			uni.showToast({
				title: '日期选择错误',
				icon: 'none'
			});
			return;
		}

		// 只保留年月日部分
		const year = date.getFullYear();
		const month = String(date.getMonth() + 1).padStart(2, '0');
		const day = String(date.getDate()).padStart(2, '0');
		formData.value.disposalDate = `${year}-${month}-${day}`;

		datePicker.value.show = false;
	};
</script>

<style lang="scss" scoped>
	.dispose-add-page {
		background-color: #f5f5f5;
		min-height: 100vh;
		padding-bottom: 120rpx;
	}

	.form-card {
		background-color: #fff;
		margin: 20rpx;
		padding: 0 30rpx;
		border-radius: 12rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
	}

	.form-item {
		display: flex;
		align-items: center;
		padding: 30rpx 0;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.form-item:last-child {
		border-bottom: none;
	}

	.label {
		width: 200rpx;
		font-size: 28rpx;
		color: #333;
	}

	.required::before {
		content: '*';
		color: #f56c6c;
		margin-right: 4rpx;
	}

	.value {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: space-between;
		font-size: 28rpx;
		color: #333;
	}

	.readonly {
		color: #999;
	}

	.picker-text {
		color: #333;
	}

	.attachment-section,
	.asset-section {
		background-color: #fff;
		margin: 20rpx;
		padding: 20rpx 30rpx 30rpx;
		border-radius: 12rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
	}

	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		margin-bottom: 20rpx;
	}

	.attachment-info {
		font-size: 24rpx;
		color: #999;
		margin-bottom: 20rpx;
	}

	.upload-btn {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 200rpx;
		height: 70rpx;
		background-color: #2979ff;
		color: #fff;
		font-size: 28rpx;
		border-radius: 8rpx;
		margin-bottom: 20rpx;
	}

	.attachment-list {
		display: flex;
		flex-direction: column;
	}

	.attachment-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #eee;
		font-size: 28rpx;
	}

	.section-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.asset-count {
		font-size: 26rpx;
		color: #666;
	}

	.asset-list {
		display: flex;
		flex-direction: column;
	}

	.asset-item {
		display: flex;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #eee;
	}

	.asset-img-container {
		width: 120rpx;
		height: 120rpx;
		margin-right: 20rpx;
	}

	.asset-img {
		width: 100%;
		height: 100%;
		border-radius: 8rpx;
		background-color: #f0f0f0;
	}

	.asset-info {
		flex: 1;
	}

	.asset-name {
		font-size: 30rpx;
		font-weight: bold;
		margin-bottom: 10rpx;
	}

	.asset-detail {
		font-size: 26rpx;
		color: #666;
		margin-bottom: 6rpx;
	}

	.asset-action {
		display: flex;
		align-items: center;
		padding: 0 10rpx;
	}

	.empty-tip {
		text-align: center;
		padding: 40rpx 0;
		color: #999;
		font-size: 28rpx;
	}

	.footer-btn {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		padding: 20rpx 30rpx;
		background-color: #fff;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.btn-group {
		display: flex;
		justify-content: space-between;
	}

	.btn {
		flex: 1;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		font-size: 30rpx;
		border-radius: 8rpx;
		margin: 0 10rpx;
	}

	.add-btn {
		background-color: #4cd964;
		color: #fff;
	}

	.reset-btn {
		background-color: #f0f0f0;
		color: #333;
	}

	.submit-btn {
		background-color: #2979ff;
		color: #fff;
	}
</style>